package com.riddle.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.riddle.model.Article;
import com.riddle.model.Category;
import com.riddle.model.Comment;
import com.riddle.service.ArticleService;
import com.riddle.service.CommentService;
import com.riddle.util.JsonUtil;
import com.riddle.vmodel.VMsg;

@Controller
@RequestMapping("/articles")
public class ArticlesController {

	@Resource
	private ArticleService articleService;
	
	@Resource
	private CommentService commentService;
	
	@RequestMapping()
	public String index() {
		return "articles";
	}
	
	@RequestMapping("/article/{id}")
	public ModelAndView article(@PathVariable Long id) {
		Article article = articleService.query(id);
		return new ModelAndView("article", "article", article);
	}
	
	@RequestMapping(value="/categorylist", produces="application/json;charset=utf-8")
	@ResponseBody
	public String list() {
		List<Category> res = articleService.getCategoriesWithCount();
		return JsonUtil.toJson(res);
	}
	
	@RequestMapping(value="/recent", produces="application/json;charset=utf-8")
	@ResponseBody
	public String recent() {
		List<Article> res = articleService.getRecentArticles();
		return JsonUtil.toJson(res);
	}
	
	@RequestMapping("/category/{id}")
	public ModelAndView category(@PathVariable Long id) {
		Category category = articleService.getCategoryWithArticles(id);
		return new ModelAndView("category", "category", category);
	}
	
	@RequestMapping(value="/addcomment", produces="application/json;charset=utf-8")
	@ResponseBody
	public String addComment(Comment comment) {
		comment.setCreateTime(new Date());
		commentService.insert(comment);
		VMsg msg = new VMsg();
		msg.setMessage("success");
		return JsonUtil.toJson(msg);
	}
	
	@RequestMapping(value="/comments/{id}", produces="application/json;charset=utf-8")
	@ResponseBody
	public String comments(@PathVariable Long id) {
		return JsonUtil.toJson(commentService.getCommentOfArticle(id));
	}
	
	@RequestMapping(value="/recentcomments", produces="application/json;charset=utf-8")
	@ResponseBody
	public String recentComments() {
		return JsonUtil.toJson(commentService.getRecentComment());
	}
}
